<template>
  <div class="pagination">
    <button :disabled="pageNo == 1" @click="$emit('getPageNo',pageNo-1)">上一页</button>
    <button v-if="!(pageRange.start == 1)" @click="$emit('getPageNo',1)" :class="{'active':pageNo == 1}">1</button>
    <button v-if="pageRange.start > 2">···</button>

    <button 
    v-for="(page,index) in pageRange.end" 
    :key="index" 
    v-if="page >= pageRange.start"
    @click="$emit('getPageNo',page)"
    :class="{'active':pageNo == page}"
    >{{ page }}</button>
    
    <button v-if="pageRange.end < totalPage - 1">···</button>
    <button v-if="pageRange.end < totalPage " @click="$emit('getPageNo',totalPage)" :class="{'active':pageNo == totalPage}">{{totalPage}}</button>
    <button :disabled="pageNo == totalPage" @click="$emit('getPageNo',pageNo+1)">下一页</button>
    
    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>

  export default {
    name: "Pagination",
    //  <!-- 传递参数 总数据条数 当前页 页容量 连续显示页码 -->
   props:['total','pageNo','pageSize','continue'],
   computed:{
    // 计算总页数
    totalPage(){
      return Math.ceil(this.total/this.pageSize);
    },
    // 计算当前页连续显示的页码起始位置和结束位置
    pageRange(){
      // 起始位置
      let start=0
      // 结束位置
      let end=0

      // 特殊情况：总页数小于或等于连续显示页码数
      if(this.continue > this.totalPage){
         start=1
         end=this.totalPage
      }else{

        start = this.pageNo - parseInt(this.continue/2)
        end = this.pageNo + parseInt(this.continue/2)

        //如果起始位置小于1
        if(start < 1){
          start = 1
          end = this.continue
        }

        //如果结束位置大于总页数
        if(end > this.totalPage){
          end = this.totalPage
          start = this.totalPage - this.continue + 1
        }
      }
      return {start,end}
    }
    
   }
  }
</script>

<style lang="less" scoped>
  .pagination {
    text-align: center;
    button {
      margin: 0 5px;
      background-color: #f4f4f5;
      color: #606266;
      outline: none;
      border-radius: 2px;
      padding: 0 4px;
      vertical-align: top;
      display: inline-block;
      font-size: 13px;
      min-width: 35.5px;
      height: 28px;
      line-height: 28px;
      cursor: pointer;
      box-sizing: border-box;
      text-align: center;
      border: 0;

      &[disabled] {
        color: #c0c4cc;
        cursor: not-allowed;
      }

      &.active {
        cursor: not-allowed;
        background-color: #409eff;
        color: #fff;
      }
    }
  }
  .active{
    background-color: #409eff;
  }
</style>
